<template>
  <a-modal
    :title="title"
    :width="450"
    :visible="visible"
    :closable="false"
    :maskClosable="false">
    <template slot="footer">
      <a-button type="primary" @click="selectOk">确认</a-button>
    </template>

    <a-form-model>
      <a-form-model-item v-if="isMultiTenant" :labelCol="{span:4}" :wrapperCol="{span:20}" style="margin-bottom:10px" :validate-status="validate_status1">
        <a-tooltip placement="topLeft" >
          <a-avatar style="backgroundColor:#2F54EB" icon="gold" />
        </a-tooltip>

        <a-select @change="handleTenantChange" :class="{'valid-error':validate_status1=='error'}" placeholder="请选择登录租户" style="margin-left:10px;width: 80%">
          <a-icon slot="suffixIcon" type="gold" />
          <a-select-option v-for="d in tenantList" :key="d.id" :value="d.id">
            {{ d.name }}
          </a-select-option>
        </a-select>
      </a-form-model-item>


      <a-form-model-item v-if="isMultiDepart || (!isMultiDepart && beShow)" :labelCol="{span:4}" :wrapperCol="{span:20}" style="margin-bottom:10px" :validate-status="validate_status2">
        <a-tooltip placement="topLeft" >
          <a-avatar style="backgroundColor:#2F54EB;" icon="gold" />
        </a-tooltip>

        <a-select @change="handleDepartChange" :class="{'valid-error':validate_status2=='error'}" placeholder="请选择登录组织" style="margin-left:10px;width: 80%">
          <a-icon slot="suffixIcon" type="gold" />
          <a-select-option v-for="d in departList" :key="d.id" :value="d.orgCode">
            {{ d.departName }}
          </a-select-option>
        </a-select>
      </a-form-model-item>

      <a-form-model-item v-if="isMultiWarehouse" :labelCol="{span:4}" :wrapperCol="{span:20}" style="margin-bottom:10px" :validate-status="validate_status3">
        <a-tooltip placement="topLeft" >
          <a-avatar style="backgroundColor:#2F54EB;" icon="gold" />
        </a-tooltip>

        <a-select @change="handleWarehouseChange" :class="{'valid-error':validate_status3=='error'}" placeholder="请选择登录仓库" style="margin-left:10px;width: 80%">
          <a-icon slot="suffixIcon" type="gold" />
          <a-select-option v-for="d in warehouseList" :key="d.id" :value="d.id">
            {{ d.name }}
          </a-select-option>
        </a-select>
      </a-form-model-item>

    </a-form-model>
  </a-modal>
</template>

<script>

import Vue from 'vue'
import { putAction } from '@/api/manage'
import { USER_INFO } from '@/store/mutation-types'

export default {
    name: 'LoginSelectTenant',
    data(){
      return {
        visible: false,
        isMultiDepart:false,
        isNoneDepart:false,
        beShow:false,
        departList:[],
        isMultiTenant:false,
        tenantList:[],
        isMultiWarehouse:false,
        warehouseList:[],
        username:'',
        orgCode:'',
        warehouseId:'',
        warehouseName:'',
        tenant_id:'',
        validate_status1: "",
        validate_status2: "",
        validate_status3: "",
      }
    },
    computed:{
      title(){
        // if(this.isMultiDepart && this.isMultiTenant){
        if(this.isMultiDepart && this.isMultiWarehouse){
          return '请选择组织和仓库'
        }else if(this.isMultiDepart && !this.isMultiWarehouse){
          return '请选择组织'
        }else if(!this.isMultiDepart && this.isMultiWarehouse){
          return '请选择仓库'
          //NEVER
        }else if(!this.isMultiDepart && this.isMultiWarehouse){
          return '请选择租户'
        }
      }
    },
    methods:{
      clear(){
        this.departList = []
        this.tenantList = []
        this.warehouseList = []
        this.visible=false
        this.validate_status1=''
        this.validate_status2=''
        this.validate_status3=''
      },
      bizDepart(loginResult){
        let multi_depart = loginResult.multi_depart
        let warehouseInfo = loginResult.warehouseInfo
        if (Array.isArray(warehouseInfo)) {
          if (warehouseInfo.length > 1) {
            this.beShow = true;
          }
        }
        //0:无部门 1:一个部门 2:多个部门
        if(multi_depart==0){
          this.$notification.warn({
            message: '提示',
            description: `您尚未归属组织,请确认账号信息!`,
          });
          this.isMultiDepart = false
          this.isNoneDepart = true
          return;
        }else if(multi_depart==2){
          this.visible=true
          this.isMultiDepart = true
          this.departList = loginResult.departs
        }else {
          this.departList = loginResult.departs
          this.isMultiDepart = false
          if(this.beShow){
            this.isMultiWarehouse = true
            this.visible=true
          }
        }
      },
      bizTenantList(loginResult) {
        let tenantList = loginResult.tenantList
        if (Array.isArray(tenantList)) {
          if (tenantList.length === 0) {
            this.isMultiTenant = false
          } else if (tenantList.length === 1) {
            this.tenant_id = tenantList[0].id
            this.isMultiTenant = false
          } else {
            this.visible = true
            this.isMultiTenant = true
            this.tenantList = tenantList
          }
        }
      },
      bizWarehouseList(warehouseInfo){
        this.warehouseList = [];
        if (Array.isArray(warehouseInfo)) {
          if (warehouseInfo.length === 0) {
            this.isMultiWarehouse = false
          }else if (warehouseInfo.length === 1) {
            this.warehouseId = warehouseInfo[0].id
            this.isMultiWarehouse = false
          }else {
            this.visible = true
            this.isMultiWarehouse = true
            this.warehouseList = warehouseInfo
          }
        }
      },
      show(loginResult){
        this.clear();
        this.bizDepart(loginResult);
        if(!this.isNoneDepart) {
          let user = Vue.ls.get(USER_INFO)
          this.username = user.username
          this.bizTenantList(loginResult);
          if (this.visible === false) {
            this.$store.dispatch('saveTenant', this.tenant_id);
            this.$emit('success',1)
          }
        }else{
          this.$emit('success',-1)
        }
      },
      requestFailed (err) {
        this.$notification[ 'error' ]({
          message: '登录失败',
          description: ((err.response || {}).data || {}).message || err.message || "请求出现错误，请稍后再试",
          duration: 4,
        });
        this.loginBtn = false;
      },

      departResolve(){
        return new Promise((resolve, reject)=>{
          if(this.isMultiDepart===false){
            resolve();
          }else{
            let obj = {
              orgCode:this.orgCode,
              username:this.username
            }
            putAction("/sys/selectDepart",obj).then(res=>{
              if(res.success){
                const userInfo = res.result.userInfo;
                Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000);
                this.$store.commit('SET_INFO', userInfo);
                //console.log("---切换组织机构---userInfo-------",store.getters.userInfo.orgCode);
                resolve();
              }else{
                this.requestFailed(res)
                this.$store.dispatch('Logout');
                reject();
              }
            })
          }
        })
      },
      selectOk(){
        if(this.isMultiTenant && !this.tenant_id){
          this.validate_status1='error'
          return false
        }
        if(this.isMultiDepart && !this.orgCode){
          this.validate_status2='error'
          return false
        }
        if(this.isMultiWarehouse && !this.warehouseId){
          this.validate_status3='error'
          return false
        }
        this.departResolve().then(()=>{
          this.$store.dispatch('saveTenant', this.tenant_id);
          this.$emit('success',1)
        }).catch(()=>{
          console.log('登录选择出问题')
        })
      },
      handleTenantChange(e){
        this.validate_status1 = ''
        this.tenant_id = e
      },
      handleDepartChange(e){
        this.validate_status2 = ''
        this.orgCode = e
        return new Promise((resolve, reject)=>{
          if(this.isMultiDepart===false && this.beShow === false){
            resolve();
          }else{
            let obj = {
              orgCode:this.orgCode,
              username:this.username
            }
            putAction("/sys/selectDepart",obj).then(res=>{
              if(res.success){
                const userInfo = res.result.userInfo;
                const warehouseInfo = res.result.warehouseInfo;
                Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000);
                this.$store.commit('SET_INFO', userInfo);
                if(warehouseInfo){
                  this.bizWarehouseList(warehouseInfo);
                  this.$store.dispatch('saveBeWarehouse', "Y");
                }else{
                  this.warehouseList = [];
                  this.isMultiWarehouse = false;
                  this.$store.dispatch('saveBeWarehouse', "N");
                }
                //console.log("---切换组织机构---userInfo-------",store.getters.userInfo.orgCode);
                resolve();
              }else{
                this.requestFailed(res)
                this.$store.dispatch('Logout');
                reject();
              }
            })
          }
        })
      },
      handleWarehouseChange(e){
        this.validate_status3 = ''
        this.warehouseId = e
        for (let i = 0; i < this.warehouseList.length; i++) {
           let tMap = this.warehouseList[i];
           if(tMap.id === this.warehouseId){
             this.$store.dispatch('saveWarehouse', tMap);
           }
        }
      }
    }
  }
</script>

<style scoped>

</style>